package com.citycloud.ccuap.tc.sync.aspect;

import com.citycloud.ccuap.commons.json.JSONData;
import com.citycloud.ccuap.commons.sys.entity.SysDeptment;
import com.citycloud.ccuap.commons.sys.entity.SysProject;
import com.citycloud.ccuap.commons.sys.project.IProjectService;
import com.citycloud.ccuap.tc.sync.dto.DepartmentMessageDTO;
import com.citycloud.ccuap.tc.sync.mapper.AspectDepartmentMapper;
import com.citycloud.ccuap.tc.sync.constant.GlobalSyncOperation;
import com.citycloud.ccuap.tc.sync.constant.GlobalSyncType;
import com.citycloud.ccuap.tc.sync.dto.SyncDataDto;
import com.citycloud.ccuap.tc.sync.service.IMessageService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class DeptAddAspect {
    @Autowired
    private IProjectService projectService;

    @Autowired
    private IMessageService messageService;

    @Autowired
    @Lazy
    private AspectDepartmentMapper deptmentMapper;


    @Pointcut("execution(* com.citycloud.ccuap.commons.sys.deptment.DeptmentController.add())")
    public void addDept() {
    }

    @AfterReturning(value = "addDept()", returning = "key")
    public void doAddDept(JoinPoint joinPoint, Object key) throws Throwable {
        if (key instanceof JSONData) {
            JSONData jsonData = (JSONData) key;
            if (jsonData.getData() instanceof SysDeptment) {
                SysDeptment dept = (SysDeptment) jsonData.getData();

                /*维护全路径*/
                deptmentMapper.updateFullPath(null);
                deptmentMapper.completeFullPath(null);
                deptmentMapper.updateFullIdPath(null);
                deptmentMapper.completeFullIdPath(null);
                sendMessage(dept);
            }
        }
    }

    private void sendMessage(SysDeptment department) {
        if (department.getProjectId() != null) {
            SysProject project = projectService.findById(department.getProjectId());
            if (project != null && project.getMqOff()) {
                DepartmentMessageDTO departmentMessageDTO = new DepartmentMessageDTO();
                departmentMessageDTO.build(department);

                SyncDataDto<DepartmentMessageDTO> result = SyncDataDto.of(GlobalSyncType.OBJECT_TYPE_DEPT,
                        GlobalSyncOperation.CREATED, department.getProjectId(), departmentMessageDTO);
                messageService.sendMessageByTopic(result,GlobalSyncType.TOPIC_USER_DEPT);
            }
        }
    }

}
